#!/usr/bin/env python


import os, re
from waflib import Logs, Errors


def options(opt):
	opt.add_option('--disable-uniaudiodec', action = 'store_true', default = False, help = 'disable uniaudio decoder [default: enabled]')
	opt.add_option('--disable-mp3encoder', action = 'store_true', default = False, help = 'disable mp3 encoder [default: enabled]')


def configure_audio_codec_path(conf):
	fslcodec_libdirvar = conf.check_cfg(package = 'libfslaudiocodec', args = '--variable=libdir', msg = 'Searching fslcodec plugin directory', okmsg = 'found', errmsg = 'not found', mandatory = 0).strip()
	if not fslcodec_libdirvar:
		Logs.pprint('RED', 'could not find fsl codec path')
		return

	conf.define("IMX_AUDIO_CODEC_PATH", fslcodec_libdirvar)
	conf.env["IMX_AUDIO_CODEC_PATH"] = fslcodec_libdirvar


def configure_mp3_encoder(conf):
	# The "uselib = 'FSLAUDIOCODEC'" part applies the libdir
	# from the pkg-config .pc file to the check_cc() call,
	# which might be necessary if the encoder library is not
	# in a default location
	if conf.check_cc(lib = '_mp3_enc_arm12_elinux', uselib = 'FSLAUDIOCODEC', uselib_store = 'FSLAUDIOCODEC', mandatory = 0):
		conf.env['MP3_ENCODER_ENABLED'] = 1
		conf.define('WITH_MP3_ENCODER', 1)
		Logs.pprint('GREEN', 'mp3 encoder will be built')
	else:
		Logs.pprint('RED', 'mp3 encoder will not be built')


def configure(conf):
	if conf.options.disable_uniaudiodec and conf.options.disable_mp3encoder:
		return

	if not conf.env['WITH_GSTAUDIO']:
		return

	if conf.check_cfg(package = 'libfslaudiocodec', uselib_store = 'FSLAUDIOCODEC', args = '--cflags --libs', mandatory = 0):
		configure_audio_codec_path(conf)

		if not conf.options.disable_uniaudiodec:
			if conf.env['IMX_AUDIO_CODEC_PATH']:
				Logs.pprint('GREEN', 'uniaudio decoder will be built')
				conf.env['UNIAUDIO_DECODER_ENABLED'] = 1
				conf.define('WITH_UNIAUDIO_DECODER', 1)
			else:
				Logs.pprint('RED', 'no imx-codec path found - not building uniaudio decoder')


		if not conf.options.disable_mp3encoder:
			configure_mp3_encoder(conf)
	else:
		Logs.pprint('RED', 'audio plugins will not be built - libfslaudiocodec package not found')


def build(bld):
	base_source = ['plugin.c']
	extra_source = []

	if not bld.env['WITH_GSTAUDIO']:
		return

	if bld.env['UNIAUDIO_DECODER_ENABLED']:
		extra_source += ['uniaudio_codec.c', 'uniaudio_decoder.c']
	if bld.env['MP3_ENCODER_ENABLED']:
		extra_source += ['mp3_encoder.c']

	if extra_source:
		bld(
			features = ['c', bld.env['CLIBTYPE']],
			includes = ['.', '../..'],
			uselib = bld.env['COMMON_USELIB'] + ['IMX_ASRC', 'KERNEL_HEADERS', 'DL', 'FSLAUDIOCODEC'],
			use = 'gstimxcommon',
			target = 'gstimxaudio',
			source = base_source + extra_source,
			install_path = bld.env['PLUGIN_INSTALL_PATH']
		)

